package com.sff.module {
	import com.sff.core.ILoadable;
	
	import com.sff.core.IModule;
	import com.sff.core.sff_internal;
	import com.sff.events.ModuleEvent;
	
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.utils.getQualifiedClassName;	
	import com.sff.system.ModuleSystem;
	
	public class Module extends Sprite implements IModule {
		
		protected var _system : ModuleSystem;		
		protected var _gcEligible : Boolean = false;
		
		public function Module() {
		}

		//run -> getLoadebles -> open -> onOpen
		protected function run() : void {
			
		}
		
		public function getLoadables() : ILoadable {
			return null;
		}
		
		public function get system() : ModuleSystem {
			return _system;	
		}

		//cleanUp -> close -> onClose -> dispose		
		public function cleanUp( himself : Boolean = true ) : void {
			if( _gcEligible ) {
				return;
			}
			
			system.sff_internal::_scan();
			
			if( himself ) {
				sff_internal::_dispose();
			}
		}
		
		protected function dispose() : void {
			throw new Error( "dispose() method must be override in "+ getQualifiedClassName( this ) );
		}

		sff_internal function _init( system : ModuleSystem ) : void {
			_system = system;
			_system.resizeManager.addEventListener( Event.RESIZE, onResize, false, 10 );
			
			_gcEligible = false;
		}
		
		sff_internal function _run() : void {
			run();
		}

		sff_internal function _dispose() : void {
			dispatchEvent( new ModuleEvent( ModuleEvent.REMOVED, this, false, false ) );
			
			_system.resizeManager.removeEventListener( Event.RESIZE, onResize );
			
			dispose( );
			
			_system.dispose( );
			_system = null;
			_gcEligible = true;
		}

		
		public function open() : void {
			onOpen();
		}
		
		protected function onOpen() : void {
			dispatchEvent( new Event( Event.OPEN ) );
		}
		
		public function close() : void {
			onClosed();
		}

		protected function onClosed() : void {
			dispatchEvent( new Event( Event.CLOSE ) );
		}

		protected function onResize(evt : Event ) : void {
			x = system.resizeManager.x;
			y = system.resizeManager.y;
		}	
		
		public function requestDrawing( flag : Boolean ) : void {
			_system.sff_internal::_willDraw( flag );
		}
	}
}
